package com.laoxu.java.multithread;

/**
 * 让当前线程等待，直到调用join()方法的线程执行完毕。这样可以确保主线程在子线程完成后再继续执行
 */
public class JoinExample {
    public static void main(String[] args) {
        // 创建两个线程
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 5; i++) {
                    System.out.println("线程1正在运行：" + i);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 5; i++) {
                    System.out.println("线程2正在运行：" + i);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        // 启动线程
        thread1.start();
        thread2.start();

        try {
            // 主线程等待thread1执行完毕
            thread1.join();
            // 主线程等待thread2执行完毕
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("所有线程执行完毕");
    }
}
